package com.example.server.Contr;

import com.example.server.Service.PlaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/api")
public class Upload {
    @Autowired PlaceService placeService;
    @Value("${upload.path}")
    private String uploadPath;
    @PostMapping ("/upload")
    public boolean uploadFile(
            @RequestParam("locationName") String locationName,
            @RequestPart("locationImage") MultipartFile locationImage,
            @RequestParam("type") String type,
            @RequestParam("city") String city,
            @RequestParam("description") String description,
            @RequestParam("uploader") String uploader,
            @RequestParam("now") String now) {
        try {
            // 1. 生成文件名（长度在 10 以内）
            String fileName;
            boolean boo;
            do {
                fileName = generateShortFileName(); // 生成文件名
                System.out.println(fileName);
                 boo = placeService.selectplace(fileName);
            } while (boo); // TODO: 替换为你的循环条件
            String FileName = fileName+".jpg";
            // 2. 保存文件到指定路径
            Path path = Paths.get(uploadPath + FileName);
            Files.copy(locationImage.getInputStream(), path);

            // 3. 处理其他字段
            System.out.println("地点名称: " + locationName);
            System.out.println("类型: " + type);
            System.out.println("城市: " + city);
            System.out.println("地点简介: " + description);
            System.out.println("上传人: " + uploader);
            System.out.println("当前时间: " + now);
            return placeService.insertplace(locationName,FileName,type,city,uploader,now,description);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 生成一个长度在 10 以内的文件名
    private String generateShortFileName() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    }
}
